package com.ming.closeto.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ming.closeto.R;
import com.ming.closeto.adapter.CategoryAdapter;
import com.ming.closeto.adapter.EveryDayAdapter;
import com.ming.closeto.bean.CategoryBean;
import com.ming.closeto.bean.EveryDayBean;
import com.ming.closeto.entity.Constant;
import com.ming.closeto.model.AllWallpaperModel;
import com.ming.closeto.ui.CategoryActivity;
import com.ming.closeto.ui.SpecialActivity;
import com.ming.closeto.utils.GlideUtils;
import com.ming.closeto.utils.OkHttpUtils;
import com.ming.closeto.view.AutoViewPager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 壁纸
 */
public class WallpaperFragment extends Fragment {

    private LinearLayout mLoadingLayout;
    private AutoViewPager mAutoViewPager;

    private RecyclerView mCategoryRecyclerView;
    private CategoryAdapter mCategoryAdapter;
    private List<CategoryBean> mList = new ArrayList<>();

    private RecyclerView mEveryDayRecyclerView;
    private EveryDayAdapter mEveryDayAdapter;
    private List<EveryDayBean> mListEveryDay = new ArrayList<>();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_wallpaper, null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        mLoadingLayout = view.findViewById(R.id.mLoadingLayout);

        // 轮播
        mAutoViewPager = (AutoViewPager) view.findViewById(R.id.mAutoViewPager);
        mAutoViewPager.setAutoTime(2 * 1000);
        mAutoViewPager.setStartAuto(true);

        // 横向分类
        mCategoryRecyclerView = view.findViewById(R.id.mCategoryRecyclerView);
        mCategoryAdapter = new CategoryAdapter(getActivity(), mList);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mCategoryRecyclerView.setLayoutManager(linearLayoutManager);
        mCategoryRecyclerView.setAdapter(mCategoryAdapter);

        mCategoryAdapter.setOnItemClickListener(new CategoryAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(getActivity(), CategoryActivity.class);
                CategoryBean bean = mList.get(position);
                intent.putExtra("name", bean.getName());
                intent.putExtra("url", bean.getUrl());
                startActivity(intent);
            }
        });

        // 每日推荐列表
        mEveryDayRecyclerView = view.findViewById(R.id.mEveryDayRecyclerView);
        mEveryDayAdapter = new EveryDayAdapter(getActivity(), mListEveryDay);
        mEveryDayRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        mEveryDayRecyclerView.setAdapter(mEveryDayAdapter);

        mEveryDayAdapter.setOnItemClickListener(new EveryDayAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(getActivity(), SpecialActivity.class);
                EveryDayBean bean = mListEveryDay.get(position);
                intent.putExtra("name", bean.getDate());
                intent.putExtra("url", bean.getSmallUrl());
                startActivity(intent);
            }
        });

        initWallpaper();
    }

    // 初始化壁纸
    private void initWallpaper() {

        OkHttpUtils.get(Constant.WALLPAPER_URL_1, new OkHttpUtils.OnOkHttpCallback() {
            @Override
            public void onFailure(IOException e) {

            }
            @Override
            public void onFailure(String msg) {

            }
            @Override
            public void onSuccessful(String json) {
                if (!TextUtils.isEmpty(json)) {
                    parsingWallpaperJson(json);
                }
            }
        });
    }

    // 解析壁纸的Json
    private void parsingWallpaperJson(String json) {
        AllWallpaperModel model = new Gson().fromJson(json, AllWallpaperModel.class);

        // 由于接口有变化，拿到的数据只有一组，所以下面3个分类使用同一组数据
        initSpecial(model.getResults());
        initCategory(model.getResults());
        initEveryday(model.getResults());

        // 隐藏加载
        mLoadingLayout.setVisibility(View.GONE);

    }

    // 初始化轮播图
    private void initSpecial(List<AllWallpaperModel.ResultsBean> special) {
        if (!special.isEmpty()) {
            for (int i=0; i<special.size(); i++) {
                View view = View.inflate(getActivity(), R.layout.layout_special_item,null);
                TextView tv_title = view.findViewById(R.id.tv_title);
                TextView tv_content = view.findViewById(R.id.tv_content);
                ImageView iv_img = view.findViewById(R.id.iv_img);

                final String name = special.get(i).getWho();
                final  String desc = special.get(i).getType();
                final String url = special.get(i).getUrl();

                tv_title.setText(name);
                tv_content.setText(desc);
                GlideUtils.loadImageviewCenterCrop(getActivity(), special.get(i).getUrl(), iv_img);

                mAutoViewPager.setView(view);

                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), SpecialActivity.class);
                        intent.putExtra("title", name);
                        intent.putExtra("url", url);
                        startActivity(intent);
                    }
                });
            }
        }
    }

    // 初始化横向分类
    private void initCategory(List<AllWallpaperModel.ResultsBean> category) {
        if (!category.isEmpty() && category.size() > 0) {
            for (int i=0; i<category.size(); i++) {
                AllWallpaperModel.ResultsBean bean = category.get(i);

                CategoryBean categoryBean = new CategoryBean();
                categoryBean.setName(bean.getWho());
                categoryBean.setCover(bean.getUrl());
                categoryBean.setUrl(bean.getUrl());

                mList.add(categoryBean);
            }
            mCategoryAdapter.notifyDataSetChanged();
        }
    }

    // 初始化每天壁纸推荐
    private void initEveryday(List<AllWallpaperModel.ResultsBean> everyday) {
        if (!everyday.isEmpty() && everyday.size() > 0) {
            for (int i=0; i<everyday.size(); i++) {
                AllWallpaperModel.ResultsBean resultsBean = everyday.get(i);
                EveryDayBean bean = new EveryDayBean();
                bean.setDate(resultsBean.getDesc());
                bean.setSmallUrl(resultsBean.getUrl());
                bean.setBigUrl(resultsBean.getUrl());
                mListEveryDay.add(bean);
            }
            mEveryDayAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) { // 如果已经隐藏  就关闭轮播
            if (mAutoViewPager != null) {
                if (mAutoViewPager.getStratAuto()) {
                    mAutoViewPager.setStartAuto(false);
                }
            }
        } else { // 如果显示 而不在轮播， 则改为自动轮播
            if (mAutoViewPager != null) {
                if (!mAutoViewPager.getStratAuto()) {
                    mAutoViewPager.setStartAuto(true);
                }
            }
        }
    }
}
